package com.hwtx.soa.registry;

import com.google.common.collect.Lists;
import com.hzgj.bcl.soa.config.RegistryDef;
import com.hzgj.bcl.soa.registry.Registry;
import com.hzgj.bcl.soa.registry.RegistryFactory;
import com.hzgj.bcl.soa.registry.RegistryUpdater;
import com.hzgj.bcl.soa.util.Constants;
import com.hzgj.bcl.util.reg.EtcdExtClient;

import java.net.URI;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class EtcdRegistryFactory implements RegistryFactory {
    private Registry registry = null;
    private RegistryUpdater registryUpdater = null;
    private Object lock1 = new Object();
    private Object lock2 = new Object();
    private EtcdExtClient etcdExtClient;

    @Override
    public Registry getRegistry(RegistryDef registryDef) {
        if (registry == null) {
            synchronized (lock1) {
                if (registry == null) {
                    registry = new EtcdRegistry(getClient(registryDef), registryDef.getTtl(),registryDef.getMode());
                }
            }
        }
        return registry;
    }

    @Override
    public RegistryUpdater getRegistryUpdater(RegistryDef registryDef) {
        if (registryUpdater == null) {
            synchronized (lock2) {
                if (registryUpdater == null) {
                    registryUpdater = new EtcdRegistryUpdater(getClient(registryDef), registryDef.getTtl());
                }
            }
        }
        return registryUpdater;
    }

    @Override
    public String getName() {
        return Constants.ETCD_REGISTRY;
    }


    private EtcdExtClient getClient(RegistryDef registryDef) {
        if (etcdExtClient != null) {
            return etcdExtClient;
        }
        String addr = registryDef.getAddress();
        List<URI> uris = Lists.newArrayList();
        for (String url : addr.split(",")) {
            if (!url.startsWith("http://")) {
                url = "http://" + url;
            }
            uris.add(URI.create(url));
        }

        try {
            etcdExtClient = new EtcdExtClient(registryDef.getTimeout(), TimeUnit.SECONDS, uris);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return etcdExtClient;
    }
}
